package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-03-23
 * Time: 18:55
 */

// 强制登陆检测
@WebServlet("/force")
public class ForceLogin extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 当页面加载的时候, 发起请求获取当前页面的登陆状态, 如果未登陆则强制跳转到登陆页面
        // 一个页面可以拥有多个 ajax 请求

        // 约定前端: GET/force
        // 约定响应  HTTP/1.1 200 OK
        // 返回当前约定对象 userId: ?  username: ? 未登录返回 userId 为 0(无效数据) 即谁登录返回谁

        ObjectMapper objectMapper = new ObjectMapper();
        resp.setContentType("application/json; charset = utf8");

        // 1. 获取会话对象
        // 此时用户未登陆则拿不到会话
        HttpSession session = req.getSession(false);
        if(session == null) {
            User user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            // 将空对象返回
            resp.getWriter().write(respJson);
            resp.sendRedirect("login.html");
            return;
        }

        // 存在会话 即有 HttpSession 对象 通过 key 获取 value;
        User user = (User) session.getAttribute("user");
        if(user == null) {
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            resp.sendRedirect("login.html");

            return;
        }

        // 取出 user 对象后直接返回
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
